import pandas as pd
import json
from pyecharts import options as opts
from pyecharts.charts import Bar, Timeline

def get_model_top10_data(df):
    try:
        # 数据清洗：确保数据类型正确
        df_clean = df.copy()
        
        # 使用正确的列名（根据您的app.py中的映射）
        df_clean['年份'] = pd.to_numeric(df_clean['年份'], errors='coerce')
        df_clean['月份'] = pd.to_numeric(df_clean['月份'], errors='coerce')
        df_clean['销量'] = pd.to_numeric(df_clean['销量'], errors='coerce')
        
        # 处理售价数据
        def extract_price(price_str):
            try:
                if pd.isna(price_str) or price_str == '':
                    return 0.0
                # 提取售价区间的最低值
                price_str = str(price_str)
                if '-' in price_str:
                    return float(price_str.split('-')[0])
                else:
                    return float(price_str)
            except (ValueError, IndexError, AttributeError):
                return 0.0

        df_clean['售价（万元）'] = df_clean['售价(万元)'].apply(extract_price)
        
        # 过滤无效数据
        df_clean = df_clean.dropna(subset=['年份', '销量', '车型'])
        df_clean = df_clean[df_clean['销量'] > 0]

        # 创建时间线对象
        tl = Timeline()
        tl.add_schema(
            play_interval=2000,
            is_auto_play=True,
            is_loop_play=True,
            is_rewind_play=True,
            is_timeline_show=True,
            orient="vertical",
            pos_left="null",
            pos_right="5",
            pos_top="20",
            pos_bottom="20",
            width="60",
            height="300"
        )

        # 遍历2015年到2023年
        years_with_data = []
        for year in range(2015, 2024):
            # 筛选当年的数据
            yearly_data = df_clean[df_clean['年份'] == year]
            
            if len(yearly_data) == 0:
                continue
                
            # 按销量降序排列，取前10名
            top_10 = yearly_data.nlargest(10, '销量')
            
            if len(top_10) == 0:
                continue
                
            years_with_data.append(year)

            # 创建柱状图
            bar = (
                Bar()
                .add_xaxis(top_10['车型'].tolist())
                .add_yaxis(
                    "销量", 
                    top_10['销量'].tolist(), 
                    label_opts=opts.LabelOpts(
                        position="right",
                        formatter="{c}"
                    ),
                    itemstyle_opts=opts.ItemStyleOpts(
                        color="#1e88e5"
                    )
                )
                .add_yaxis(
                    "售价（万元）", 
                    top_10['售价（万元）'].tolist(), 
                    label_opts=opts.LabelOpts(
                        position="right",
                        formatter="{c}万"
                    ),
                    itemstyle_opts=opts.ItemStyleOpts(
                        color="#ff9800"
                    )
                )
                .reversal_axis()  # 反转轴，使柱状图水平显示
                .set_global_opts(
                    title_opts=opts.TitleOpts(
                        title=f"{year}年销量排名前10的车型及其售价",
                        title_textstyle_opts=opts.TextStyleOpts(
                            font_size=16,
                            font_weight="bold"
                        )
                    ),
                    yaxis_opts=opts.AxisOpts(
                        name="销量/售价",
                        name_location="middle",
                        name_gap=50
                    ),
                    xaxis_opts=opts.AxisOpts(
                        name="车型",
                        axislabel_opts=opts.LabelOpts(
                            rotate=0,
                            interval=0
                        )
                    ),
                    legend_opts=opts.LegendOpts(
                        pos_top="10%",
                        pos_right="10%"
                    ),
                    tooltip_opts=opts.TooltipOpts(
                        trigger="axis",
                        axis_pointer_type="shadow"
                    )
                )
            )

            # 将柱状图添加到时间线
            tl.add(bar, f"{year}年")

        if len(years_with_data) == 0:
            return {
                'success': False,
                'error': '没有找到有效的数据'
            }

        # 将时间线图表转换为 JSON 数据
        chart_json = tl.dump_options_with_quotes()

        return {
            'success': True,
            'chart_data': chart_json,
            'years_count': len(years_with_data),
            'years': years_with_data
        }
        
    except Exception as e:
        return {
            'success': False,
            'error': f'处理数据时发生错误: {str(e)}'
        }